package com.hazesoft.hdclib;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

/**
 * This class provides functionality to download layout files from a web
 * server using the HTTP Internet protocol.
 * @author Keagan Ladds
 */
public class HttpLayoutDownloader extends HazeLayoutDownloader {

	private static final String DEBUG_MESSAGE_TAG = "HttpLayoutDownloader";
	
	@Override
	public boolean Download(String localFilePath) {
		boolean boolSuccess = false;
		HttpURLConnection urlConnection = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try
		{
			URL url = new URL((String)this.mDownloaderParameters);
			urlConnection = (HttpURLConnection)url.openConnection();
			
			// Try and connect to the HTTP server using the specified URL
			urlConnection.connect();
			
			// If the server does not respond with a HTTP_OK that means something went 
			// wrong so we must return false.
			if(urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
			{
				Log.e(DEBUG_MESSAGE_TAG, "Failed to download Layout file. Server responsed with '" + urlConnection.getResponseMessage() + "'");
				return false;
			}
			
			// If we get here that means the server has the file for us so we can 
			// download it and save it to a local file.
			
			inputStream = urlConnection.getInputStream();
			outputStream = new FileOutputStream(localFilePath);
			
			byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = inputStream.read(data)) != -1) {
                total += count;
                outputStream.write(data, 0, count);
            }
            
            boolSuccess = true;
		}
		catch(Exception ex)
		{
			boolSuccess = false;
		}
		finally
		{
			try
			{
				if(outputStream != null)
					outputStream.close();
				
				if(inputStream != null)
					inputStream.close();
				
				if(urlConnection != null)
					urlConnection.disconnect();
			}
			catch(Exception ex){}
		}
		
		return boolSuccess;
	}

	@Override
	public boolean RequireDownload(String localFilePath) {
		// TODO Auto-generated method stub
		return true;
	}

}
